using System.Diagnostics;
using System.Drawing.Imaging;
using VideoRecorder.Util;

namespace VideoRecorder.Media;

/// <summary>
/// 屏幕捕获
/// </summary>
public class ScreenCapturer {
    private const string TAG = $"[{nameof(ScreenCapturer)}]";

    private readonly TimedIntervalTask _captureTask;
    private readonly object _locker = new();
    private volatile bool _running;

    public bool IsRunning => _running;

    public int Fps { get; set; } = 15;
    public Screen Screen { get; set; }
    public event Action<Bitmap> CapturedFrame;

    public ScreenCapturer() {
        _captureTask = new TimedIntervalTask(CaptureTask, 1000);
    }

    public void Start() {
        if (_running) return;
        _running = true;
        var fps = Fps;
        var interval = WebCamHelper.GetFpsIntervalTime(ref fps);
        Fps = fps;
        _captureTask.IntervalTime = interval;
        _captureTask.Startup();
        Debug.WriteLine($"{TAG} 开始捕获屏幕: {fps}fps");
    }

    public void Stop() {
        if (!_running) return;
        _running = false;
        _captureTask.Stop();
        Debug.WriteLine($"{TAG} 停止捕获屏幕: {Fps}fps");
    }

    private void CaptureTask() {
        try {
            var screen = Screen ?? Screen.PrimaryScreen;
            if (screen == null) return;
            var bounds = screen.Bounds;
            var rect = new Rectangle(bounds.X, bounds.Y, bounds.Width, bounds.Height);
            var bitmap = new Bitmap(rect.Width, rect.Height, PixelFormat.Format24bppRgb);
            using var g = Graphics.FromImage(bitmap);
            g.CopyFromScreen(rect.Location, Point.Empty, rect.Size);
            lock (_locker) {
                CapturedFrame?.Invoke(bitmap);
            }
        } catch (Exception ex) {
            Debug.WriteLine($"{TAG} 捕获屏幕异常: {ex.Message}");
        }
    }
}
